﻿using Logistics.Manager;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using SAP.Middleware.Connector;

namespace Logistics
{
    public partial class frmSAPImport : Form
    {
        ListViewColumnSorter lvwColumnSorter = new ListViewColumnSorter();
        private TC_OWI_FILE obj_tc_owi = new TC_OWI_FILE();
        private TC_OWR_FILE obj_tc_owr = new TC_OWR_FILE();
        private TC_OWS_FILE obj_tc_ows = new TC_OWS_FILE();
        private TC_OWW_FILE obj_tc_oww = new TC_OWW_FILE();
        private SAP_Data sapData = new SAP_Data();

        private List<Model.SAPDataModel> SAPDatas;

        private bool isLoadSAPData = false;
        private bool isImportSAPData = false;


        /// <summary>
        /// 用户所拥有的物流公司列表
        /// </summary>
        private List<Model.TC_OWI_FILE> user_owi_ulist;
        public frmSAPImport()
        {
            InitializeComponent();
            this.listInfo.ListViewItemSorter = lvwColumnSorter;
            ImageList imgList = new ImageList();
            imgList.ImageSize = new Size(1, 20);//分别是宽和高
            listInfo.SmallImageList = imgList;
            SAPDatas = new List<Model.SAPDataModel>();

        }
        private void listInfo_ColumnClick(object sender, ColumnClickEventArgs e)
        {
            if (e.Column == lvwColumnSorter.SortColumn)
            {
                if (lvwColumnSorter.Order == SortOrder.Ascending)
                {
                    lvwColumnSorter.Order = SortOrder.Descending;
                }
                else
                {
                    lvwColumnSorter.Order = SortOrder.Ascending;
                }
            }
            else
            {
                lvwColumnSorter.SortColumn = e.Column;
                lvwColumnSorter.Order = SortOrder.Ascending;
            }
            this.listInfo.Sort();
        }
        private void AddListviewItem(Model.SAPDataModel model)
        {
            ListViewItem item = null;
            item = new ListViewItem();
            item.Text = model.l_type;
            item.SubItems.Add(model.l_tc_owr001);
            item.SubItems.Add(model.l_tc_owr002);
            item.SubItems.Add(model.l_tc_owr003);
            item.SubItems.Add(model.l_tc_owr004);
            item.SubItems.Add(model.l_tc_owr005);
            if (model.l_tc_owr006.HasValue)
                item.SubItems.Add(model.l_tc_owr006.Value.ToString("yyyy-MM-dd"));
            else
                item.SubItems.Add(string.Empty);
            item.SubItems.Add(model.l_tc_owr009);
            item.SubItems.Add(model.l_tc_owr010);
            item.SubItems.Add(model.l_tc_owr016);
            this.listInfo.Items.Add(item);
        }
        private void frmSAPImport_Load(object sender, EventArgs e)
        {
            BindCmbData();
            dpDate.Value = DateTime.Now;

        }
        #region 绑定基础数据
        private void BindCmbData()
        {
            string l_user = MyForms.User.UserName;
            user_owi_ulist = obj_tc_owi.User_GetList(l_user);
            var tc_owi = new Model.TC_OWI_FILE();

            tc_owi.TC_OWI002 = "请选择";
            tc_owi.TC_OWI001 = null;
            user_owi_ulist.Insert(0, tc_owi);
            tc_owi_comb.DataSource = user_owi_ulist;
            tc_owi_comb.DisplayMember = "TC_OWI002";
            tc_owi_comb.ValueMember = "TC_OWI001";
            tc_owi_comb.SelectedIndex = 0;
        }
        #endregion

        private void butquery_Click(object sender, EventArgs e)
        {

            if (this.objBGWorker.IsBusy)
            {
                return;
            }
            this.listInfo.Items.Clear();
            this.pbReport.Value = 0;
            pbReport.Visible = true;
            isImportSAPData = false;
            this.objBGWorker.RunWorkerAsync();
            //  }
            //   else
            //   {
            //      BindData();
            //   }
        }

        private void btnImport_Click(object sender, EventArgs e)
        {
            if (this.objBGWorker.IsBusy)
            {
                return;
            }
            this.pbReport.Value = 0;
            pbReport.Visible = true;
            isImportSAPData = true;
            this.objBGWorker.RunWorkerAsync();
        }

        private void sel_all_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem item in listInfo.Items)
            {
                item.Checked = true;
            }
        }

        private void sel_non_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem item in listInfo.Items)
            {
                item.Checked = false;
            }
        }

        private void sel_return_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem item in listInfo.Items)
            {
                item.Checked = !item.Checked;
            }
        }

        private void objBGWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            //InitTestData();

            if (!isImportSAPData)
                QuerySAPData();
            else
                ImportSAPData();
        }

        /// <summary>
        /// 开始查询数据
        /// </summary>
        private void QuerySAPData()
        {
            SAPDatas.Clear();

            //转储订单 psub01
            objBGWorker.ReportProgress(10, "");
            var list = sapData.GetPomigoInfo("1");
            SAPDatas.AddRange(list);
            objBGWorker.ReportProgress(20, list);

            //转储订单 psub02
            list = sapData.GetPomigoInfo("2");
            SAPDatas.AddRange(list);
            objBGWorker.ReportProgress(40, list);


            //物料凭证
            list = sapData.GetRkpfExport();
            SAPDatas.AddRange(list);
            objBGWorker.ReportProgress(60, list);
            //预付凭证
            list = sapData.GetMsegExport();
            SAPDatas.AddRange(list);
            objBGWorker.ReportProgress(80, list);


            //交货单
            list = sapData.GetDelivery();
            SAPDatas.AddRange(list);
            objBGWorker.ReportProgress(100, list);



        }

        /// <summary>
        /// 导入SAP数据
        /// </summary>
        private void ImportSAPData()
        {
            SAPDatas.Clear();

            objBGWorker.ReportProgress(10, "");
            var list = sapData.GetPomigoInfo("1");
            SAPDatas.AddRange(list);
            objBGWorker.ReportProgress(20, list);

            list = sapData.GetPomigoInfo("2");
            SAPDatas.AddRange(list);
            objBGWorker.ReportProgress(40, list);


            list = sapData.GetRkpfExport();
            SAPDatas.AddRange(list);
            objBGWorker.ReportProgress(60, list);

            list = sapData.GetMsegExport();
            SAPDatas.AddRange(list);
            objBGWorker.ReportProgress(80, list);

            list = sapData.GetDelivery();
            SAPDatas.AddRange(list);
            objBGWorker.ReportProgress(100, list);

        }

        private void objBGWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            if (e.ProgressPercentage == 100)
            {
                isLoadSAPData = true;
                pbReport.Visible = false;
                if (!isImportSAPData)
                    BindQueryData();
                else
                    ImportData();
            }
            this.pbReport.Value = e.ProgressPercentage;
        }

        private void objBGWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {

        }

        private void frmSAPImport_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (this.objBGWorker.IsBusy)
                this.objBGWorker.CancelAsync();
        }

        /// <summary>
        /// 绑定数据
        /// </summary>
        private void BindQueryData()
        {

            string l_tc_owi001 = null;
            if (tc_owi_comb.SelectedIndex > 0)
                l_tc_owi001 = tc_owi_comb.SelectedValue.ToString();

            var query = SAPDatas.AsQueryable();
            var owi001s = user_owi_ulist.Select(m => m.TC_OWI001);
            if (string.IsNullOrWhiteSpace(l_tc_owi001))
            {
                query = query.Where(m => owi001s.Contains(m.l_tc_owr009));
            }
            else
                query = query.Where(m => m.l_tc_owr009 == l_tc_owi001);


            if (dpDate.LockUpdateChecked)
            {
                var l_date = dpDate.Value.Date;
                query = query.Where(m => m.l_tc_owr006 == l_date);
            }
            this.listInfo.Items.Clear();
            this.listInfo.BeginUpdate();
            foreach (var item in query)
            {
                if (string.IsNullOrEmpty(item.l_tc_owr002))
                {
                    continue;
                }
                AddListviewItem(item);

            }
            this.listInfo.EndUpdate();
            labCount.Text = query.Count().ToString();
        }

        /// <summary>
        /// 导入SAP数据
        /// </summary>
        private void ImportData()
        {
            //判断记录目录在不在
            string g_error_dir = System.Environment.CurrentDirectory + "\\LOG";
            if (Directory.Exists(g_error_dir) == false)
            {
                Directory.CreateDirectory(g_error_dir);
            }
            //准备写错误LOG
            string g_error_file = g_error_dir + "\\" + "导入日志" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".txt";
            StreamWriter sw = new StreamWriter(g_error_file, true, System.Text.Encoding.GetEncoding("gb2312"));

            //insert tc_owr_file表
            int g_total1 = 0;
            int g_total2 = 0;
            int g_total3 = 0;
            int g_total4 = 0;
            int g_fail_total1 = 0;
            int g_fail_total2 = 0;
            int g_fail_total3 = 0;
            int g_fail_total4 = 0;

            string g_error_log = "";

            //准备回写
            RfcDestination SapRfcDestination_return = RfcDestinationManager.GetDestination("DEV");
            RfcRepository SapRfcRepository_return = SapRfcDestination_return.Repository;

            //数据筛选
            string l_tc_owi001 = null;
            if (tc_owi_comb.SelectedIndex > 0)
                l_tc_owi001 = tc_owi_comb.SelectedValue.ToString();

            var query = SAPDatas.AsQueryable();
            var owi001s = user_owi_ulist.Select(m => m.TC_OWI001);
            if (string.IsNullOrWhiteSpace(l_tc_owi001))
            {
                query = query.Where(m => owi001s.Contains(m.l_tc_owr009));
            }
            else
                query = query.Where(m => m.l_tc_owr009 == l_tc_owi001);


            if (dpDate.LockUpdateChecked)
            {
                var l_date = dpDate.Value.Date;
                query = query.Where(m => m.l_tc_owr006 == l_date);
            }
            this.listInfo.Items.Clear();
            this.listInfo.BeginUpdate();

            //foreach (var item in SAPDatas)
            foreach (var item in query)
            {
                var model = new Model.TC_OWR_FILE();
                if (string.IsNullOrEmpty(item.l_tc_owr002))
                {
                    continue;
                }

                /*  if (item.l_tc_owr002.ToString() != "1800011409")
                  {
                      continue;
                  }
                  */

                model.TC_OWR001 = item.l_tc_owr001;
                model.TC_OWR002 = item.l_tc_owr002;
                model.TC_OWR003 = item.l_tc_owr003;
                model.TC_OWR004 = item.l_tc_owr004;
                model.TC_OWR005 = item.l_tc_owr005;
                model.TC_OWR006 = item.l_tc_owr006;
                model.TC_OWR007 = item.l_tc_owr007;
                model.TC_OWR008 = item.l_tc_owr008;
                model.TC_OWR009 = item.l_tc_owr009;
                model.TC_OWR010 = item.l_tc_owr010;
                model.TC_OWR0101 = item.l_tc_owr0101;
                model.TC_OWR011 = item.l_tc_owr011;
                model.TC_OWR012 = item.l_tc_owr012;
                model.TC_OWR013 = item.l_tc_owr013;
                model.TC_OWR014 = item.l_tc_owr014;
                model.TC_OWR015 = item.l_tc_owr015;
                model.TC_OWR016 = item.l_tc_owr016;
                model.TC_OWR017 = item.l_tc_owr017;
                model.TC_OWR018 = item.l_tc_owr018;
                model.TC_OWR019 = item.l_tc_owr019;
                model.TC_OWR020 = item.l_tc_owr020;
                model.TC_OWR021 = item.l_tc_owr021;
                model.TC_OWR0131 = item.l_tc_owr0131;
                model.TC_OWR022 = item.l_tc_owr022;
                model.TC_OWR0191 = item.l_tc_owr0191;
                model.TC_OWR0132 = item.l_tc_owr0132;
                model.TC_OWR0133 = item.l_tc_owr0133;
                model.TC_OWR023 = item.l_tc_owr023;
                model.TC_OWR024 = item.l_tc_owr024;
                model.TC_OWR025 = item.l_tc_owr025;
                model.TC_OWR026 = item.l_tc_owr026;
                model.TC_OWR027 = item.l_tc_owr027;

                //判断是否有重复的情况。如果是1和D的代表还没处理，直接删掉重新导入；如果是其它，就报错
                string l_tc_owr019 = obj_tc_owr.Del(model);

                if (l_tc_owr019.ToString() == "0")
                {

                    //插入tc_owr_file
                    obj_tc_owr.Add(model);
                    if (item.l_type == "转储订单")
                    {
                        g_total1 = g_total1 + 1;

                        //转储订单回写ZTMM009K表头值
                        IRfcFunction zmmrfc_pomigo_fun_return = SapRfcRepository_return.CreateFunction("ZMMRFC_POMIGO");
                        IRfcTable KDara_w = zmmrfc_pomigo_fun_return.GetTable("IT_ZTMM009K");
                        IRfcTable KDara_p = zmmrfc_pomigo_fun_return.GetTable("IT_ZTMM009P");
                        IRfcTable lDara = zmmrfc_pomigo_fun_return.GetTable("IT_LOG");
                        IRfcStructure KDara_w_s = null;
                        KDara_w_s = SapRfcRepository_return.GetStructureMetadata("ZTMM009K").CreateStructure();
                        KDara_w_s.SetValue("Mandt", item.ZTMM009K_Mandt);
                        KDara_w_s.SetValue("Ebeln", item.ZTMM009K_Ebeln);
                        KDara_w_s.SetValue("Ekorg", item.ZTMM009K_Ekorg);
                        KDara_w_s.SetValue("Bsart", item.ZTMM009K_Bsart);
                        KDara_w_s.SetValue("Lifnr", item.ZTMM009K_Lifnr);
                        KDara_w_s.SetValue("Lifn2", item.ZTMM009K_Lifn2);
                        KDara_w_s.SetValue("Bedat", item.ZTMM009K_Bedat);
                        KDara_w_s.SetValue("Call_Type", item.ZTMM009K_Call_Type);
                        KDara_w_s.SetValue("Zpointf", item.ZTMM009K_Zpointf);
                        KDara_w.Append(KDara_w_s);

                        //插入 tc_ows_file
                        var tc_ows_query = SAPDatas.AsQueryable();
                        tc_ows_query = tc_ows_query.Where(m => m.l_tc_ows001 == item.l_tc_owr002);
                        tc_ows_query = tc_ows_query.Where(m => m.l_tc_ows000 == item.l_tc_owr001);
                        foreach (var tc_ows_item in tc_ows_query)
                        {
                            var tc_ows_model = new Model.TC_OWS_FILE();
                            tc_ows_model.TC_OWS000 = tc_ows_item.l_tc_ows000;
                            tc_ows_model.TC_OWS001 = tc_ows_item.l_tc_ows001;
                            tc_ows_model.TC_OWS002 = tc_ows_item.l_tc_ows002;
                            tc_ows_model.TC_OWS003 = tc_ows_item.l_tc_ows003;
                            tc_ows_model.TC_OWS004 = tc_ows_item.l_tc_ows004;
                            tc_ows_model.TC_OWS005 = tc_ows_item.l_tc_ows005;
                            tc_ows_model.TC_OWS006 = tc_ows_item.l_tc_ows006;
                            tc_ows_model.TC_OWS007 = tc_ows_item.l_tc_ows007;
                            tc_ows_model.TC_OWS008 = tc_ows_item.l_tc_ows008;
                            tc_ows_model.TC_OWS009 = tc_ows_item.l_tc_ows009;
                            tc_ows_model.TC_OWS010 = tc_ows_item.l_tc_ows010;
                            tc_ows_model.TC_OWS011 = tc_ows_item.l_tc_ows011;
                            tc_ows_model.TC_OWS012 = tc_ows_item.l_tc_ows012;
                            tc_ows_model.TC_OWS013 = tc_ows_item.l_tc_ows013;
                            tc_ows_model.TC_OWS014 = tc_ows_item.l_tc_ows014;
                            tc_ows_model.TC_OWS019 = tc_ows_item.l_tc_ows019;
                            tc_ows_model.TC_OWS022 = tc_ows_item.l_tc_ows022;
                            obj_tc_ows.Add(tc_ows_model);
                            obj_tc_ows.Upd(tc_ows_model, tc_ows_item.l_outdt);

                            //准备回写资料
                            IRfcStructure KDara_p_s = null;
                            KDara_p_s = SapRfcRepository_return.GetStructureMetadata("ZTMM009P").CreateStructure();
                            KDara_p_s.SetValue("Mandt", tc_ows_item.ZTMM009P_Mandt);
                            KDara_p_s.SetValue("Ebeln", tc_ows_item.ZTMM009P_Ebeln);
                            KDara_p_s.SetValue("Ebelp", tc_ows_item.ZTMM009P_Ebelp);
                            KDara_p_s.SetValue("Matnr", tc_ows_item.ZTMM009P_Matnr);
                            KDara_p_s.SetValue("Menge", tc_ows_item.ZTMM009P_Menge);
                            KDara_p_s.SetValue("Meins", tc_ows_item.ZTMM009P_Meins);
                            KDara_p_s.SetValue("Charg", tc_ows_item.ZTMM009P_Charg);
                            KDara_p_s.SetValue("Werks", tc_ows_item.ZTMM009P_Werks);
                            KDara_p_s.SetValue("Lgort", tc_ows_item.ZTMM009P_Lgort);
                            KDara_p_s.SetValue("Bwart", tc_ows_item.ZTMM009P_Bwart);
                            KDara_p_s.SetValue("Outdt", tc_ows_item.ZTMM009P_Outdt);
                            KDara_p_s.SetValue("Call_Type", tc_ows_item.ZTMM009P_Call_Type);
                            KDara_p_s.SetValue("Zpointf", tc_ows_item.ZTMM009P_Zpointf);
                            KDara_p.Append(KDara_p_s);

                        }




                        //开始回写传入结构INPUT    上线的时候开启
                        /*
                        string dd = "";
                        zmmrfc_pomigo_fun_return.SetValue("ZPOINTF", item.ZTMM009K_Zpointf);
                        zmmrfc_pomigo_fun_return.SetValue("CALL_TYPE", "W");
                        zmmrfc_pomigo_fun_return.SetValue("SUBRC", dd);
                        zmmrfc_pomigo_fun_return.SetValue("IT_LOG", lDara);
                        zmmrfc_pomigo_fun_return.SetValue("IT_ZTMM009K", KDara_w);
                        zmmrfc_pomigo_fun_return.SetValue("IT_ZTMM009P", KDara_p);
                        zmmrfc_pomigo_fun_return.Invoke(SapRfcDestination_return);
                       
                        IRfcTable KDara_p_return = zmmrfc_pomigo_fun_return.GetTable("IT_ZTMM009P");
                        for (int i = 0; i < KDara_p_return.Count; i++)
                        {
                            if (KDara_p_return.GetString("Zzflag") == "E")
                            {
                                g_fail_total1 = g_fail_total1 + 1;
                                g_error_log = g_error_log + "\n" + "转储物流 单据编号:" + KDara_p_return.GetString("Ebeln").ToString() + "错误，错误原因:" + KDara_p_return.GetString("Zzmess").ToString();
                            }


                        } 
                        */
                    }

                    if ((item.l_type == "物料凭证"))
                    {
                        g_total2 = g_total2 + 1;
                        //物料凭证回写ZSMMRFC_PKPF_EXPORT表头值
                        IRfcFunction zmmrfc_rkpf_export_return = SapRfcRepository_return.CreateFunction("ZMMRFC_RKPF_EXPORT");
                        IRfcTable KDara_w = zmmrfc_rkpf_export_return.GetTable("EX_TAB");
                        IRfcStructure KDara_w_s = null;
                        KDara_w_s = SapRfcRepository_return.GetStructureMetadata("ZSMMRFC_PKPF_EXPORT").CreateStructure(); //EX_TAB?
                        KDara_w_s.SetValue("Bwart", item.ZSMMRFC_PKPF_EXPORT_Bwart);
                        KDara_w_s.SetValue("Rsdat", item.ZSMMRFC_PKPF_EXPORT_Rsdat);
                        KDara_w_s.SetValue("Werks", item.ZSMMRFC_PKPF_EXPORT_Werks);
                        KDara_w_s.SetValue("Rsnum", item.ZSMMRFC_PKPF_EXPORT_Rsnum);
                        KDara_w_s.SetValue("Rspos", item.ZSMMRFC_PKPF_EXPORT_Rspos);
                        KDara_w_s.SetValue("Matnr", item.ZSMMRFC_PKPF_EXPORT_Matnr);
                        KDara_w_s.SetValue("Zcss", item.ZSMMRFC_PKPF_EXPORT_Zcss);
                        KDara_w.Append(KDara_w_s);

                        var tc_ows_model = new Model.TC_OWS_FILE();
                        tc_ows_model.TC_OWS000 = item.l_tc_ows000;
                        tc_ows_model.TC_OWS001 = item.l_tc_ows001;
                        tc_ows_model.TC_OWS002 = item.l_tc_ows002;
                        tc_ows_model.TC_OWS003 = item.l_tc_ows003;
                        tc_ows_model.TC_OWS004 = item.l_tc_ows004;
                        tc_ows_model.TC_OWS005 = item.l_tc_ows005;
                        tc_ows_model.TC_OWS006 = item.l_tc_ows006;
                        tc_ows_model.TC_OWS007 = item.l_tc_ows007;
                        tc_ows_model.TC_OWS008 = item.l_tc_ows008;
                        tc_ows_model.TC_OWS009 = item.l_tc_ows009;
                        tc_ows_model.TC_OWS010 = item.l_tc_ows010;
                        tc_ows_model.TC_OWS011 = item.l_tc_ows011;
                        tc_ows_model.TC_OWS012 = item.l_tc_ows012;
                        tc_ows_model.TC_OWS013 = item.l_tc_ows013;
                        tc_ows_model.TC_OWS014 = item.l_tc_ows014;
                        tc_ows_model.TC_OWS019 = item.l_tc_ows019;
                        tc_ows_model.TC_OWS022 = item.l_tc_ows022;
                        obj_tc_ows.Add(tc_ows_model);

                        //开始回写传入结构INPUT    上线的时候开启
                        /*
                        int l_total_records = 0;
                        zmmrfc_rkpf_export_return.SetValue("ZPSINTF", "PSRE01");
                        zmmrfc_rkpf_export_return.SetValue("CALL_TYPE", "W");
                        zmmrfc_rkpf_export_return.SetValue("TOTAL_RECORDS",l_total_records);
                        zmmrfc_rkpf_export_return.SetValue("EX_TAB", KDara_w);
                        zmmrfc_rkpf_export_return.Invoke(SapRfcDestination_return);

                        } */


                    }
                    if (item.l_type == "预留凭证")
                    {
                        g_total3 = g_total3 + 1;
                        //物料凭证回写ZSMMRFC_PKPF_EXPORT表头值
                        IRfcFunction zmmrfc_mesg_export_return = SapRfcRepository_return.CreateFunction("ZMMRFC_MSEG_EXPORT");
                        IRfcTable KDara_w = zmmrfc_mesg_export_return.GetTable("MSEG_TAB");
                        IRfcStructure KDara_w_s = null;
                        KDara_w_s = SapRfcRepository_return.GetStructureMetadata("ZSMMRFC_MSEG_EXPORT").CreateStructure(); //EX_TAB?
                        KDara_w_s.SetValue("Budat", item.ZMMRFC_MSEG_EXPORT_Budat);
                        KDara_w_s.SetValue("Cpudt", item.ZMMRFC_MSEG_EXPORT_Cpudt);
                        KDara_w_s.SetValue("Xblnr", item.ZMMRFC_MSEG_EXPORT_Xblnr);
                        KDara_w_s.SetValue("Usnam", item.ZMMRFC_MSEG_EXPORT_Usnam);
                        KDara_w_s.SetValue("Mblnr", item.ZMMRFC_MSEG_EXPORT_Mblnr);
                        KDara_w_s.SetValue("Mjahr", item.ZMMRFC_MSEG_EXPORT_Mjahr);
                        KDara_w_s.SetValue("Zeile", item.ZMMRFC_MSEG_EXPORT_Zeile);
                        KDara_w_s.SetValue("Bwart", item.ZMMRFC_MSEG_EXPORT_Bwart);
                        KDara_w_s.SetValue("Matnr", item.ZMMRFC_MSEG_EXPORT_Matnr);
                        KDara_w_s.SetValue("Lfimg", item.ZMMRFC_MSEG_EXPORT_Lfimg);
                        KDara_w_s.SetValue("Meins", item.ZMMRFC_MSEG_EXPORT_Meins);
                        KDara_w_s.SetValue("Charg", item.ZMMRFC_MSEG_EXPORT_Charg);
                        KDara_w_s.SetValue("Werks", item.ZMMRFC_MSEG_EXPORT_Werks);
                        KDara_w_s.SetValue("Lgort", item.ZMMRFC_MSEG_EXPORT_Lgort);
                        KDara_w_s.SetValue("Kostl", item.ZMMRFC_MSEG_EXPORT_Kostl);
                        KDara_w.Append(KDara_w_s);


                        var tc_ows_model = new Model.TC_OWS_FILE();
                        tc_ows_model.TC_OWS000 = item.l_tc_ows000;
                        tc_ows_model.TC_OWS001 = item.l_tc_ows001;
                        tc_ows_model.TC_OWS002 = item.l_tc_ows002;
                        tc_ows_model.TC_OWS003 = item.l_tc_ows003;
                        tc_ows_model.TC_OWS004 = item.l_tc_ows004;
                        tc_ows_model.TC_OWS005 = item.l_tc_ows005;
                        tc_ows_model.TC_OWS006 = item.l_tc_ows006;
                        tc_ows_model.TC_OWS007 = item.l_tc_ows007;
                        tc_ows_model.TC_OWS008 = item.l_tc_ows008;
                        tc_ows_model.TC_OWS009 = item.l_tc_ows009;
                        tc_ows_model.TC_OWS010 = item.l_tc_ows010;
                        tc_ows_model.TC_OWS011 = item.l_tc_ows011;
                        tc_ows_model.TC_OWS012 = item.l_tc_ows012;
                        tc_ows_model.TC_OWS013 = item.l_tc_ows013;
                        tc_ows_model.TC_OWS014 = item.l_tc_ows014;
                        tc_ows_model.TC_OWS019 = item.l_tc_ows019;
                        tc_ows_model.TC_OWS022 = item.l_tc_ows022;
                        obj_tc_ows.Add(tc_ows_model);

                        //开始回写传入结构INPUT    上线的时候开启
                        /*
                        int l_total_records = 0;
                        zmmrfc_mesg_export_return.SetValue("CALL_TYPE", "W");
                        zmmrfc_mesg_export_return.SetValue("TOTAL_RECORDS",l_total_records);
                        zmmrfc_mesg_export_return.SetValue("MSEG_TAB", KDara_w);
                        zmmrfc_mesg_export_return.Invoke(SapRfcDestination_return);
                        */

                    }
                    if (item.l_type == "交货单")
                    {
                        g_total4 = g_total4 + 1;

                        //转储订单回写ZTMM009K表头值
                        IRfcFunction zsdrfc_delivery_fun_return = SapRfcRepository_return.CreateFunction("ZSDRFC_DELIVERY");
                        IRfcTable KDara_w = zsdrfc_delivery_fun_return.GetTable("IT_ZTSD001K");
                        IRfcTable KDara_p = zsdrfc_delivery_fun_return.GetTable("IT_ZTSD001P");
                        IRfcTable lDara = zsdrfc_delivery_fun_return.GetTable("IT_LOG");
                        IRfcStructure KDara_w_s = null;
                        KDara_w_s = SapRfcRepository_return.GetStructureMetadata("ZTSD001K").CreateStructure();
                        KDara_w_s.SetValue("Mandt", item.ZTSD001K_Mandt);
                        KDara_w_s.SetValue("Inftid", item.ZTSD001K_Inftid);
                        KDara_w_s.SetValue("Vbeln", item.ZTSD001K_Vbeln);
                        KDara_w_s.SetValue("Kunag", item.ZTSD001K_Kunag);
                        KDara_w_s.SetValue("Lifnr1", item.ZTSD001K_Lifnr1);
                        KDara_w_s.SetValue("Lifnr2", item.ZTSD001K_Lifnr2);
                        KDara_w_s.SetValue("Z_Status", item.ZTSD001K_Z_Status);
                        KDara_w.Append(KDara_w_s);

                        //插入tc_oww_file
                        var tc_oww_query = SAPDatas.AsQueryable();
                        tc_oww_query = tc_oww_query.Where(m => m.l_tc_oww000 == item.l_tc_owr001);
                        tc_oww_query = tc_oww_query.Where(m => m.l_tc_oww001 == item.l_tc_owr002);
                        foreach (var tc_ows_item in tc_oww_query)
                        {
                            var tc_oww_model = new Model.TC_OWW_FILE();
                            tc_oww_model.TC_OWW000 = item.l_tc_oww000;
                            tc_oww_model.TC_OWW001 = item.l_tc_oww001;
                            tc_oww_model.TC_OWW002 = item.l_tc_oww002;
                            tc_oww_model.TC_OWW003 = item.l_tc_oww003;
                            tc_oww_model.TC_OWW004 = item.l_tc_oww004;
                            if (Convert.ToDecimal(tc_oww_model.TC_OWW004) == 0)
                            {
                                continue;
                            }
                            obj_tc_oww.Add(tc_oww_model);
                        }


                        //插入 tc_ows_file
                        var tc_ows_query = SAPDatas.AsQueryable();
                        tc_ows_query = tc_ows_query.Where(m => m.l_tc_ows001 == item.l_tc_owr002);
                        foreach (var tc_ows_item in tc_ows_query)
                        {
                            var tc_ows_model = new Model.TC_OWS_FILE();
                            tc_ows_model.TC_OWS000 = item.l_tc_owr001;
                            tc_ows_model.TC_OWS001 = tc_ows_item.l_tc_ows001;
                            tc_ows_model.TC_OWS002 = tc_ows_item.l_tc_ows002;
                            tc_ows_model.TC_OWS003 = tc_ows_item.l_tc_ows003;
                            tc_ows_model.TC_OWS004 = tc_ows_item.l_tc_ows004;
                            tc_ows_model.TC_OWS005 = tc_ows_item.l_tc_ows005;
                            tc_ows_model.TC_OWS006 = tc_ows_item.l_tc_ows006;
                            tc_ows_model.TC_OWS007 = tc_ows_item.l_tc_ows007;
                            tc_ows_model.TC_OWS008 = tc_ows_item.l_tc_ows008;
                            tc_ows_model.TC_OWS009 = tc_ows_item.l_tc_ows009;
                            tc_ows_model.TC_OWS010 = tc_ows_item.l_tc_ows010;
                            tc_ows_model.TC_OWS011 = tc_ows_item.l_tc_ows011;
                            tc_ows_model.TC_OWS012 = tc_ows_item.l_tc_ows012;
                            tc_ows_model.TC_OWS013 = tc_ows_item.l_tc_ows013;
                            tc_ows_model.TC_OWS014 = tc_ows_item.l_tc_ows014;
                            tc_ows_model.TC_OWS019 = tc_ows_item.l_tc_ows019;
                            tc_ows_model.TC_OWS022 = tc_ows_item.l_tc_ows022;

                            obj_tc_ows.Add(tc_ows_model);


                            //准备回写资料
                            IRfcStructure KDara_p_s = null;
                            KDara_p_s = SapRfcRepository_return.GetStructureMetadata("ZTSD001P").CreateStructure();
                            KDara_p_s.SetValue("Mandt", tc_ows_item.ZTSD001P_Mandt);
                            KDara_p_s.SetValue("Vbeln", tc_ows_item.ZTSD001P_Vbeln);
                            KDara_p_s.SetValue("Posnr", tc_ows_item.ZTSD001P_Posnr);
                            KDara_p_s.SetValue("Lgort", tc_ows_item.ZTSD001P_Lgort);
                            KDara_p_s.SetValue("Pstyv", tc_ows_item.ZTSD001P_Pstyv);
                            KDara_p_s.SetValue("Matnr", tc_ows_item.ZTSD001P_Matnr);
                            KDara_p_s.SetValue("Vrkme", tc_ows_item.ZTSD001P_Vrkme);
                            KDara_p_s.SetValue("Kdmat", tc_ows_item.ZTSD001P_Kdmat);
                            KDara_p_s.SetValue("Charg", tc_ows_item.ZTSD001P_Charg);
                            KDara_p_s.SetValue("Inftid", tc_ows_item.ZTSD001P_Inftid);
                            KDara_p.Append(KDara_p_s);



                        }
                        //开始回写传入结构INPUT    上线的时候开启
                        /*
                        string dd = "";
                  
                        zsdrfc_delivery_fun_return.SetValue("CALL_TYPE", "W");
                        zsdrfc_delivery_fun_return.SetValue("ZEDITP", item.ZTSD001K_Inftid);
                        zsdrfc_delivery_fun_return.SetValue("IT_LOG", lDara);
                        zsdrfc_delivery_fun_return.SetValue("SUBRC", dd);
                        zsdrfc_delivery_fun_return.SetValue("IT_ZTSD001K", KDara_w);
                        zsdrfc_delivery_fun_return.SetValue("IT_ZTSD001P", KDara_p);
                        zsdrfc_delivery_fun_return.Invoke(SapRfcDestination_return);


                        if (dd.ToString() == "1")
                        {
                            g_fail_total4 = g_fail_total4 + 1;
                            g_error_log = g_error_log + "\n" + "交货单 单据编号:" + item.ZTSD001K_Inftid.ToString() + "错误";
                        }
                        */

                    }

                }
                else
                {
                    l_tc_owr019 = tc_owr019(l_tc_owr019.ToString());
                    if (string.IsNullOrEmpty(g_error_log))
                        g_error_log = item.l_type.ToString() + " 单据:" + item.l_tc_owr002 + "'还存在SAP，但oracle状态为" + l_tc_owr019.ToString();
                    else
                        g_error_log = g_error_log.ToString() + "\\n" + item.l_type.ToString() + " 单据:" + item.l_tc_owr002 + "'还存在SAP，但oracle状态为" + l_tc_owr019.ToString();

                }

            }

            //开始回写状态
            /*  var pomigos = SAPDatas.Where(m => m.l_type == "转储订单").ToList();
              sapData.SavePomigoInfo(pomigos);

              var msegs = SAPDatas.Where(m => m.l_type == "预留凭证").ToList();
              sapData.SaveMsegExport(msegs);

              var rkpfs = SAPDatas.Where(m => m.l_type == "物料凭证").ToList();
              sapData.SaveRkpfExport(rkpfs);

              var deliverys = SAPDatas.Where(m => m.l_type == "交货单").ToList();
              sapData.SaveDelivery(deliverys);
              */
            //写正确日志
            sw.WriteLine("正确导入：");
            sw.WriteLine("   转储订单：共" + g_total1.ToString() + "笔" + ",失败" + g_fail_total1.ToString() + "笔");
            sw.WriteLine("   预留凭证：共" + g_total2.ToString() + "笔" + ",失败" + g_fail_total2.ToString() + "笔");
            sw.WriteLine("   物料凭证：共" + g_total3.ToString() + "笔" + ",失败" + g_fail_total3.ToString() + "笔");
            sw.WriteLine("   交 货 单：共" + g_total4.ToString() + "笔" + ",失败" + g_fail_total4.ToString() + "笔");
            sw.Flush();
            //写错误日志
            if (!string.IsNullOrEmpty(g_error_log))
            {
                sw.WriteLine("错误导入：");
                sw.WriteLine(g_error_log);
                sw.Flush();
            }

            sw.Close();
            labCount.Text = SAPDatas.Count().ToString();
            MessageBox.Show("数据导入完成", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            System.Diagnostics.Process.Start(g_error_file);

        }


        private string tc_owr019(string l_tc_owr019)
        {
            switch (l_tc_owr019.ToString())
            {
                case "0":
                    l_tc_owr019 = l_tc_owr019 + ":开立";
                    break;
                case "1":
                    l_tc_owr019 = l_tc_owr019 + ":导出未处理";
                    break;
                case "2":
                    l_tc_owr019 = l_tc_owr019 + ":导出已处理";
                    break;
                case "3":
                    l_tc_owr019 = l_tc_owr019 + ":回馈未处理";
                    break;
                case "4":
                    l_tc_owr019 = l_tc_owr019 + ":回馈已处理";
                    break;
                case "5":
                    l_tc_owr019 = l_tc_owr019 + ":不导物流";
                    break;
                case "X":
                    l_tc_owr019 = l_tc_owr019 + ":作废";
                    break;
                case "D":
                    l_tc_owr019 = l_tc_owr019 + ":WMS删除";
                    break;
                case "F":
                    l_tc_owr019 = l_tc_owr019 + ":WMS接收失败";
                    break;
            }
            return l_tc_owr019.ToString();

        }

        private void CopyMenuItem_Click(object sender, EventArgs e)
        {
            if (this.listInfo.SelectedItems.Count == 0)
                return;
            var item = listInfo.SelectedItems[0];
            var str = new StringBuilder();
            str.AppendLine($"凭证种类：{item.Text}");
            str.AppendLine($"类型：{item.SubItems[1].Text}");
            str.AppendLine($"单据编号：{item.SubItems[2].Text}");
            str.AppendLine($"导出方：{item.SubItems[3].Text}");
            str.AppendLine($"送货方：{item.SubItems[4].Text}");
            str.AppendLine($"客户编号：{item.SubItems[5].Text}");
            str.AppendLine($"单据日期：{item.SubItems[6].Text}");
            str.AppendLine($"物流公司：{item.SubItems[7].Text}");
            str.AppendLine($"承送商：{item.SubItems[8].Text}");
            str.AppendLine($"备注：{item.SubItems[9].Text}");
            Clipboard.SetDataObject(str.ToString());
        }
    }
}
